﻿using System;
using System.Net;
using System.Net.NetworkInformation;

namespace CheckPortOccupied
{
    class Program
    {
        static void Main(string[] args)
        {
            string Loop;

            //do
            //{
            //    bool Occupied = PortInUse(2333);

            //    Console.WriteLine("端口2333占用情况为：" + Occupied);
            //    Console.WriteLine("");
            //    Console.WriteLine("是否重新check？请输入Y或y后回车：");

            //    Loop = Console.ReadLine();

            //    Console.WriteLine("");
            //} while (Loop == "y" || Loop == "Y");

            for (int i = 0; i <= 65535; i++)
            {
                bool Occupied = PortInUse(i);
                Console.WriteLine("端口" + i.ToString() + "占用情况为：" + Occupied);
            }

            Console.ReadLine();
        }

        public static bool PortInUse(int port)
        {
            bool inUse = false;

            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }

            return inUse;
        }
    }
}
